<?php

namespace App\Jobs;

use App\AdvertiserVideo;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class PullVideo implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $accountId;
    protected $time;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($accountId, $time = 0)
    {
        $this->accountId = $accountId;
        $this->time = $time;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $cacheKey = 'PullVideo-' . $this->accountId;
        if (Cache::has($cacheKey)){
            return ;
        }
        Cache::put($cacheKey, 1, 5);

        $advertiser['account_id'] = $this->accountId;
        $page = 1;
        $totalPage = 1;
//        Log::info("获取广告账户【".$advertiser['account_id']."】的视频资源开始");
        while (true) {
//            Log::info("获取广告账户【".$advertiser['account_id']."】的视频资源页数【". $page."】");
            $responseData = $this->getata($page, $advertiser['account_id']);

            if (isset($responseData['data']['list']) && count($responseData['data']['list']) > 0) {
                $listData = $responseData['data']['list'];
                foreach ($listData as $image) {
                    AdvertiserVideo::query()->firstOrCreate([
                        'video_id' => $image['video_id'],
                    ], [
                        'account_id' => $advertiser['account_id'],
                        'preview_url' => $image['preview_url'],
                        'type' => $image['type'],
                        'resource_created_time' => $image['created_time'] ?? 0,
                    ]);
                }
            }

            if ($page == 1) {
                $totalPage = $responseData['data']['page_info']['total_page'] ?? 0;
//                Log::info("获取广告账户【".$advertiser['account_id']."】视频资源总数【". ($responseData['data']['page_info']['total_number'] ?? 0)."】");

            }
            $page++;

            if ($page > $totalPage) {
//                Log::info("获取广告账户【".$advertiser['account_id']."】的视频资源结束");
                break;
            }
        }
    }

    private function getata(int $page = 1, $accountId)
    {
        $interface = 'videos/get';
        $url = 'https://api.e.qq.com/v3.0/' . $interface;

        $common_parameters = array (
            'access_token' => \config('app.tencent_access_token'),
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        );

        $parameters = array (
            'account_id' => $accountId,
            'filtering' => [
                ['field' => 'created_time', 'operator' => 'GREATER_EQUALS', 'values' => [strval($this->time)]],
                ['field' => 'status', 'operator' => 'EQUALS', 'values' => ['ADSTATUS_NORMAL']]
            ],
            'page' => $page,
            'page_size' => 100,
        );

        $parameters = array_merge($common_parameters, $parameters);

        foreach ($parameters as $key => $value) {
            if (!is_string($value)) {
                $parameters[$key] = json_encode($value);
            }
        }

        $request_url = $url . '?' . http_build_query($parameters);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);

            Log::error("获取视频返回错误: ", [
                'error_msg' => $error_msg,
                'error_no' => $error_no
            ]);
            return [];
//            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);

        $responseData = json_decode($response, true);
        if (!isset($responseData['code']) || $responseData['code'] != 0) {
            Log::error("获取视频返回错误: ", [
                'data' => $responseData,
                'params' => $parameters
            ]);

            return [];
        }
        return $responseData;
    }
}
